package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.validator.LengthValidator;
import com.zheng.common.validator.NotNullValidator;
import com.zheng.hr.dao.model.HrPosition;
import com.zheng.hr.rpc.api.HrPositionService;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.exception.OaException;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/1/8
 * Time: 10:50
 */
@Controller
@Api(value = "岗位管理", description = "岗位管理")
@RequestMapping("/oa/hr/position")
public class HrPositionController extends BaseController {
    //岗位级别
    private final String POSITION_LEVEL = "position_level";
    //职能类型
    private final String POSITION_TYPE = "position_type";
    @Autowired
    private HrPositionService positionService;
    @Autowired
    private UpmsApiService apiService;

    @ApiOperation(value = "获取所有岗位")
    @RequestMapping(value = "/getAllPosition", method = RequestMethod.GET)
    @ResponseBody
    public Object getAllPosition(Integer checkedNodeId, Integer id) {
        EntityWrapper<HrPosition> entityWrapper = new EntityWrapper<>();
        if (id != null) {
            entityWrapper.where("id!=" + id);
        }
        List<HrPosition> positions = positionService.selectList(entityWrapper);
        JSONArray treeArray = new JSONArray();
        for (HrPosition position : positions) {
            JSONObject treeNode = new JSONObject();
            treeNode.put("id", position.getId());
            treeNode.put("pId", position.getPid());
            treeNode.put("path", position.getPath());
            treeNode.put("name", position.getName());
            treeNode.put("open", "true");
            if (checkedNodeId != null && checkedNodeId.equals(position.getId())) {
                treeNode.put("open", true);
            }
            treeArray.add(treeNode);
        }
        return treeArray;
    }

    @ApiOperation(value = "岗位管理首页")
    @RequiresPermissions("oa:hr:position:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/hr/position/index.jsp";
    }

    @ApiOperation(value = "岗位列表")
    @RequiresPermissions("oa:hr:position:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, defaultValue = "", value = "searchText") String searchText,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       @RequestParam(required = false, value = "id") Integer id) {
        Wrapper<HrPosition> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        if (StringUtils.isNotBlank(searchText)) {
            wrapper.like("name", searchText);
        }
        if (null != id) {
            wrapper.where("id = " + id + " or path like '%," + id + ",%'");
        }
        Page<HrPosition> page = positionService.selectPage(new Page<>(pageNumber, pageSize), wrapper);
        int total = positionService.selectCount(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", page.getRecords());
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增岗位")
    @RequiresPermissions("oa:hr:position:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model, Integer pid) {
        List<HrPosition> positions = positionService.selectList(null);
        model.addAttribute("positions", JSON.toJSON(positions));
        HrPosition parentPosition = positionService.selectById(pid);
        model.addAttribute("parentPosition", parentPosition);
        return "/manage/hr/position/create.jsp";
    }

    @ApiOperation(value = "新增岗位")
    @RequiresPermissions("oa:hr:position:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(HrPosition position) {
        ComplexResult result = FluentValidator.checkAll()
                .on(position.getName(), new LengthValidator(0, 100, "岗位名称"))
                .on(position.getType(), new NotNullValidator("职能类型"))
                .on(position.getDuty(), new LengthValidator(0, 1000, "职责"))
                .on(position.getRequirement(), new LengthValidator(0, 1000, "入职要求"))
                .on(position.getDescription(), new LengthValidator(0, 1000, "描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            positionService.insertPosition(position);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, OaResultConstant.FAILED.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }


    @ApiOperation(value = "修改岗位")
    @RequiresPermissions("oa:hr:position:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Integer id, Model model) {
        HrPosition hrPosition = positionService.selectById(id);
        model.addAttribute("position", hrPosition);
        HrPosition parentPosition = positionService.selectById(hrPosition.getPid());
        if (null == parentPosition) {
            parentPosition = new HrPosition();
            parentPosition.setId(0);
            parentPosition.setName("顶级");
        }
        model.addAttribute("parentPosition", parentPosition);
        List<HrPosition> positions = positionService.selectList(null);
        model.addAttribute("positions", JSON.toJSONString(positions));
        return "/manage/hr/position/update.jsp";
    }

    @ApiOperation(value = "修改岗位")
    @RequiresPermissions("oa:hr:position:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HrPosition position) {
        ComplexResult result = FluentValidator.checkAll()
                .on(position.getName(), new LengthValidator(0, 100, "岗位名称"))
                .on(position.getType(), new NotNullValidator("职能类型"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        HrPosition parentPosition = positionService.selectById(position.getPid());
      /*  if (null != parentPosition) {
            String oldPath = parentPosition.getPath();
            String[] splitPath = oldPath.split("_");
            for (String id : splitPath) {
                if (id.equals(position.getPid().toString())) {
                    return new OaResult(OaResultConstant.FAILED, "关联失败！请更换父岗位");
                }
            }
        }*/
        String path;
        if (null != parentPosition) {
            path = parentPosition.getPath() + position.getPid() + ",";
        } else {
            path = "0,";
        }
        position.setPath(path);
        if (positionService.updateById(position)) {
            return new OaResult(OaResultConstant.SUCCESS, null);
        } else {
            return new OaResult(OaResultConstant.FAILED, OaResultConstant.FAILED.getMessage());
        }
    }

    @ApiOperation(value = "删除岗位")
    @RequiresPermissions("oa:hr:position:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        try {
            positionService.deletePositionByIds(ids);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

}
